/**
 *
 * @file
 *		heap_vasya
 *
 * @brief
 *		Heap implementation by anyav
 */
//using std::vector;
using namespace std;


#include "heap_vasya.h"
#include "../../api/heap.h"

#define Err printf

#ifdef _DEBUG
#define Dbg printf
#else
#define Dbg
#endif




heap_vasya::~heap_vasya()
{
	if( alloc_sz )
		Err("[heap] destruct not empty %p\n", alloc_sz );

	DeleteCriticalSection(&cs);
}
void* heap_vasya::alloc( size_t sz, unsigned int tag )
{

	if( ( alloc_sz + sz ) > total_limit )
	{
		Err("[heap] failed to alloc {sz=%p, tg=0x%x} sz=%p, total=%p \n",
			sz, tag, alloc_sz, total_limit );
		return NULL;
	}
	    EnterCriticalSection(&cs);

        n_size = int(sz/16)+1;
        temp = 0;
        first = n_blocks+1;
        for (i = 0; i<n_blocks;i++){
            if((i+n_size)<n_blocks){
                j = 0;
                while((j<n_size)){
                    if(!mem_map[i+j]){
                        j++;
                    }
                }
                if (j == n_size) {
                    length_map[i] = j;
                    first = i;        ///we have found where to start
                    i = n_blocks;     ///stopping for
                }
            }
        }
        if(first<n_blocks) {
            for(i=0;i<n_size;i++) {
                mem_map[i] = true;
            }
        }
    alloc_sz += sz;
    mem += first*16; //shifting pointer
    LeaveCriticalSection(&cs);
    return mem;


}

void heap_vasya::free( void* ptr )
{
    EnterCriticalSection(&cs);

    /// @todo change i and j according to ptr
    alloc_sz = 0;
    temp_ptr = (char*)ptr;
    temp = (temp_ptr-begin)/16;
    for (i=0;i<length_map[temp];i++){
        mem_map[temp+i] = false;  ///put addition HERE!
    }
    length_map[temp]=0;

    LeaveCriticalSection(&cs);


}

